﻿using B.S.BasicData.Api.Read.Application.Command.Account;
using B.S.BasicData.Api.Read.DTOs;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Account
{
    /// <summary>
    /// 查询账号分页处理类
    /// </summary>
    public class GetAccountPageHandler : IRequestHandler<GetAccountPageCommand, ApiPaging<AccountListDTO>>
    {


        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountRoleRepo;
        private readonly IBaseRepository<DepartmentModel> departmentRepo;
        private readonly ILogger<GetAccountPageHandler> logger;//Nlog组件对象

        /// <summary>
        /// 注入仓储
        /// </summary>
        /// <param name="accountRepo"></param>
        /// <param name="roleRepo"></param>
        /// <param name="accountRoleRepo"></param>
        public GetAccountPageHandler(IBaseRepository<AccountModel> accountRepo, IBaseRepository<RoleModel> roleRepo, IBaseRepository<AccountRoleModel> accountRoleRepo, IBaseRepository<DepartmentModel> departmentRepo,ILogger<GetAccountPageHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.roleRepo = roleRepo;
            this.accountRoleRepo = accountRoleRepo;
            this.departmentRepo = departmentRepo;
            this.logger = logger;
        }
        /// <summary>
        /// 查询账号分页处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<AccountListDTO>> Handle(GetAccountPageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiPaging<AccountListDTO> res = new ApiPaging<AccountListDTO>();//实例化分页响应包装类

                //四个表达式  
                var accounts = accountRepo.GetAll().Where(x => x.IsDeleted == false); //select * from accounts where isdel =false and accountname like '%wu%'
                var roles = roleRepo.GetAll().Where(x => x.IsDeleted == false);  // //select * from role where isdel =false
                var accountRole = accountRoleRepo.GetAll().Where(x => x.IsDeleted == false); //select * from accountRole where isdel =false
                var departments = departmentRepo.GetAll();

                if (!string.IsNullOrEmpty(request.AccountName))
                {
                    accounts = accounts.Where(x => x.AccountName.Contains(request.AccountName)); //模糊查询账号
                }
                if (!string.IsNullOrEmpty(request.DepartMentName))
                {
                    departments = departments.Where(x => x.DepartmentName.Contains(request.DepartMentName)); //模糊部门名称模糊查询
                }

                //linq 组合关联查询前,要先过滤数据

                var linq = from a in accounts
                           join ar in accountRole on a.Id equals ar.AccountId
                           join r in roles on ar.RoleId equals r.Id
                           join d in departments on a.DepartmentId equals d.Id
                           select new AccountListDTO
                           {
                               Id = a.Id,
                               AccountName = a.AccountName,
                               CardId = a.CardId,
                               PhoneNo = a.PhoneNo,
                               RealName = a.RealName,
                               RoleName = r.RoleName,
                               DepartmentName = d.DepartmentName,
                               Img = a.Img
                           };

                res.TotalCount = linq.Count();
                res.PageDatas = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();//为什么到这里才tolist()??

                res.Code = ApiEnum.Success;
                res.Msg = "账号分页查询成功!";
                return res;
            }
            catch (Exception e)
            {
                logger.LogError("发生异常:"+e.Message);
                throw;
            }
        }
    }
}
